/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import org.apache.log4j.Logger;
import util.DBUtil;

/**
 *
 * @author PhucAn
 */
public class ClassStudentDAO {

    Connection conn = null;
    Logger log = Logger.getLogger(ClassStudentDAO.class);
    private final String sqlReadByClassId = "select * from class_student where class_id=?";
    private final String sqlDelete = "delete from class_student where class_id=? and student_id=?";

    public int create(dto.Class cls) {
        int effectedRows = 0;
        conn = DBUtil.getConnection();
        if (conn == null) {
            return 0;
        }
        String sqlCommand = "insert into class_student(class_id, student_id)  ";
        ArrayList<dto.User> students = cls.getStudents();
        int size = students.size();
        for (int i = 0; i < size; i++) {
            if (i == 0) {
                sqlCommand += " select ?, ? ";
            } else {
                sqlCommand += " UNION ALL select ?, ? ";
            }
        }
        try {
            PreparedStatement ps = conn.prepareStatement(sqlCommand);
            for (int i = 0; i < size; i++) {
                ps.setInt(i * 2 + 1, cls.getId());
                ps.setInt(i * 2 + 2, students.get(i).getId());
            }
            effectedRows = ps.executeUpdate();
            DBUtil.disconnect();
        } catch (SQLException ex) {
            log.info(ex.getMessage());
        } catch (Exception ex) {
            log.info(ex.getMessage());
        }
        return effectedRows;
    }
    
    public int delete(int classId, int studentId) {
        int effectedRows = -1;
        conn = DBUtil.getConnection();
        if (conn == null) {
            return effectedRows;
        }     
        try {
            PreparedStatement ps = conn.prepareStatement(sqlDelete);
            ps.setInt(1, classId);
            ps.setInt(2, studentId);
            effectedRows = ps.executeUpdate();
            DBUtil.disconnect();
        } catch (SQLException ex) {
            log.info(ex.getMessage());
        } catch (Exception ex) {
            log.info(ex.getMessage());
        }
        return effectedRows;
    }
}